import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import React, { useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormInstance,
} from '@ant-design/pro-form';
import {
  addNotice,
  changeStatuNotice,
  deleteNotice,
  getAllNotice,
} from '@/service/notice';
import { formatTime } from '@/common/publicFun';

export default function NoticeContent() {
  const actionRef = useRef<ActionType>();
  const restFormRef = useRef<ProFormInstance>();
  const columns: ProColumns[] = [
    {
      title: '公告内容',
      dataIndex: 'content',
      ellipsis: true,
      copyable: true,
      // hideInSearch: true,
      align: 'left',
    },
    {
      title: '创建时间',
      dataIndex: 'create_Ts',
      hideInSearch: true,
      sorter: (a, b) => {
        return Number(a.create_Ts) - Number(b.create_Ts);
      },
      align: 'left',
      render: (_, _record) => (
        <span>{formatTime(_record.create_Ts, 'FULL_TIME')}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'statu',
      editable: false,
      valueEnum: {
        1: { text: '已启用', color: 'green' },
        0: {
          text: '已禁用',
          color: 'red',
        },
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 300,
      key: 'option',
      valueType: 'option',
      render: (_, _record, index, action) => [
        <a
          key={'changeStatu' + index}
          onClick={() => {
            handleChangeStatu({ content: _record.content });
          }}
        >
          {_record.statu ? '禁用' : '启用'}
        </a>,
        <div key={'delete' + index}>
          <Popconfirm
            key={'fghj'}
            onConfirm={() => {
              handleDeleteNotice({ content: _record.content });
            }}
            title={'请确认是否删除该内容'}
          >
            <a>删除</a>
          </Popconfirm>
        </div>,
        <div key={'detail' + index}>
          <ModalForm
            title={'公告详情'}
            trigger={<a>公告详情</a>}
            submitter={{
              render: () => {
                return [];
              },
            }}
          >
            {_record.content}
          </ModalForm>
        </div>,
      ],
    },
  ];

  async function handleChangeStatu(params: { content: string }) {
    const data = await changeStatuNotice(params);
    if (data.stat === 'ok') {
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  async function handleDeleteNotice(params: { content: string }) {
    const data = await deleteNotice(params);
    if (data.stat === 'ok') {
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  return (
    <React.Fragment>
      <ProTable
        actionRef={actionRef}
        pagination={{ pageSize: 7, current: 1, showSizeChanger: true }}
        columns={columns}
        rowKey={'content'}
        request={async (params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const data = await getAllNotice({
            offset: (params.pageSize || 7) * ((params.current || 1) - 1),
            limit: params.pageSize || 7,
            statu:
              params.statu === '1' ? 1 : params.statu === '0' ? 0 : undefined,
            content: params.content,
            ...sorter,
          });
          return data.data;
        }}
        toolBarRender={() => [
          <ModalForm<{ content: string; statu: 0 | 1 }>
            formRef={restFormRef}
            title="新建公告"
            trigger={
              <Button type="primary">
                <PlusOutlined />
                新建公告
              </Button>
            }
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (value) => {
              const data = await addNotice({ ...value });
              if (data.stat === 'ok') {
                message.success('操作成功');
                restFormRef.current?.resetFields();
                actionRef.current?.reload();
                return true;
              } else {
                message.error('操作失败，' + data.msg);
              }
            }}
          >
            <ProForm.Group>
              <ProFormTextArea
                width="lg"
                name="content"
                label="公告内容"
                placeholder="请输入内容"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                request={async () => [
                  {
                    value: 0,
                    label: '禁用',
                  },
                  {
                    value: 1,
                    label: '启用',
                  },
                ]}
                width="xs"
                name="statu"
                label="初始状态"
              />
            </ProForm.Group>
          </ModalForm>,
        ]}
      />
    </React.Fragment>
  );
}
